/**
 * 字节处理
 */
import { hilog } from "@kit.PerformanceAnalysisKit";
import { buffer, util } from "@kit.ArkTS";

export default class BytesUtils {
  /**
   * hex 转换成普通字符串
   * @param hex
   * @returns
   */
  public static hexToString(hex: string): string {
    // 校验是否是有效的16进制字符串
    // 确保字符串长度是偶数
    if (hex.length % 2 !== 0) {
      return hex;
    }

    let str = '';
    for (let i = 0; i < hex.length; i += 2) {
      // 每两个字符代表一个字节，将其转换为十进制整数，再转换为字符
      let charCode = parseInt(hex.substr(i, 2), 16);
      str += String.fromCharCode(charCode);
    }
    return str;
  }

  public static hexStrToByteArray(data: string): Uint8Array {
    hilog.debug(0x0000, "BytesUtils", '需要转换的16进制数据:' + data);
    let bytes = new Uint8Array(buffer.from(data, 'hex').buffer);
    hilog.debug(0x0000, "BytesUtils", '十六进制转Uint8Array:' + bytes);
    return bytes;
  }

  public static bytesToHexStr(bytes: Uint8Array, len: number): string {
    let hexString = '';
    let i: number;
    for (i = 0; i < len; i++) {
      let char = ('00' + bytes[i].toString(16)).slice(-2);
      hexString += char;
    }
    hilog.debug(0x0000, "BytesUtils", 'Uint8Array转十六进制:' + hexString);
    return hexString;
  }

  public static bytesToStr(bytes: Uint8Array): string {
    let textDecoderOptions: util.TextDecoderOptions = {
      fatal: false,
      ignoreBOM: true
    }
    let decodeToStringOptions: util.DecodeToStringOptions = {
      stream: false
    }
    let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
    let retStr = textDecoder.decodeToString(bytes, decodeToStringOptions);
    hilog.debug(0x0000, "BytesUtils", '字节流转成可理解的字符串:' + retStr);
    return retStr;
  }

  public static strToUtf8Str(data: string): string {
    let textEncoder = new util.TextEncoder("utf-8");
    let result = textEncoder.encodeInto(data);
    return buffer.from(result.buffer).toString()
  }
}